import { createRouter, createWebHistory } from 'vue-router'
import { getUserProfile } from '@/api/user'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
    },
    {
      path: '/forget',
      name: 'forget',
      component: () => import('@/views/RegisterView.vue'),
    },
    {
      path: '/map/:userName',
      name: 'map',
      component: () => import('@/views/MapView.vue'),
    },
  ],
})

// 设置路由守卫
router.beforeEach(async (to) => {
  if (to.name === 'login' || to.name === 'register' || to.name === 'forget') return true
  try {
    await getUserProfile()
    return true
  } catch (error) {
    console.error(error)
    ElMessage({
      message: '请先登录，错误详情请查看控制台',
      type: 'error',
      duration: 5 * 1000, //5s,默认3s
      showClose: true,
    })
    return { name: 'login' }
  }
})

export default router
